package com.gf.framework.idgenetor.config;

import com.gf.framework.common.utils.SpringContextUtil;
import com.gf.framework.idgenetor.porperties.IdGeneotrProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author gaofei
 * @date 2022/6/5 10:37
 */
@Configuration
@Component
public class IdGenetorConfig {
    @Resource
    IdGeneotrProperties idGeneotrProperties;

    private final Map<String, SnowFlakeIdGentetor> snowFlakeIdGentetorMap = new HashMap<>();

    /**
     * 全局共用一个的情况
     * @return
     */
    @Bean
    SnowFlakeIdGentetor snowFlakeIdGentetor() {
        if (idGeneotrProperties.getDataCenterId() < 0) {
            return new SnowFlakeIdGentetor(idGeneotrProperties.getWorkerId());
        }
        return new SnowFlakeIdGentetor(idGeneotrProperties.getDataCenterId(), idGeneotrProperties.getWorkerId());
    }

    /**
     * 根据不同的表获取不同的id生成器
     * @param tableName
     * @return
     */
    public SnowFlakeIdGentetor getSnowFlakeIdGentetorByTableName(String tableName) {
        SnowFlakeIdGentetor snowFlakeIdGentetor = snowFlakeIdGentetorMap.get(tableName);
        if (snowFlakeIdGentetor != null) {
            return snowFlakeIdGentetor;
        }

        synchronized (snowFlakeIdGentetorMap) {
            snowFlakeIdGentetor = snowFlakeIdGentetorMap.get(tableName);
            if (snowFlakeIdGentetor == null) {
                if (idGeneotrProperties.getDataCenterId() < 0) {
                    snowFlakeIdGentetor = new SnowFlakeIdGentetor(idGeneotrProperties.getWorkerId());
                }
                else {
                    snowFlakeIdGentetor = new SnowFlakeIdGentetor(idGeneotrProperties.getDataCenterId(), idGeneotrProperties.getWorkerId());
                }
                snowFlakeIdGentetorMap.put(tableName, snowFlakeIdGentetor);
            }
        }
        return snowFlakeIdGentetor;
    }
}
